import 'package:flutter/cupertino.dart';
import 'package:x3_component_core/models/base_bottom_sheet_selector_model.dart';

class BaseBottomSheetMultipleController extends ChangeNotifier {
  /// 数据类
  List<BaseBottomSheetSelectorModel> items;

  /// 选中数据
  List<BaseBottomSheetSelectorModel> _selected = [];

  List<BaseBottomSheetSelectorModel> get selected => _selected;

  set selected(dynamic value) {
    if (value is List<BaseBottomSheetSelectorModel>) {
      _selected = value;
      return;
    }
    if (value is List<Map>) {
      _selected = BaseBottomSheetSelectorModel.getListBaseSelectDownItem(value);
      return;
    }
    if (value is List<Map<String, dynamic>>) {
      _selected = value.map((e) => BaseBottomSheetSelectorModel.fromJson(e)).toList();
      return;
    }

    ///有可能是只选择了一个的情况，并且数据是Map类型的
    if (value is Map) {
      _selected = BaseBottomSheetSelectorModel.getListBaseSelectDownItem([value]);
      return;
    }
  }

  ///
  List<BaseBottomSheetSelectorModel> oldSelected = [];

  /// 选中数据判断
  List<String> get selectedListString => selected.map((e) => e.toString()).toList();

  /// 提示语
  String hit;

  /// 显示本文
  String get selectedText {
    if (selected.length == 0) return hit;
    return selected.map((e) => e.value).toList().join(',');
  }

  BaseBottomSheetMultipleController({@required this.items, List<BaseBottomSheetSelectorModel> selected, this.hit = '请选择'}) : assert(items != null) {
    if (selected != null) {
      this.selected = selected;
      this.oldSelected = List<BaseBottomSheetSelectorModel>.from(selected);
    }
  }

  /// 工厂模式构建控制器
  factory BaseBottomSheetMultipleController.formJson(List<Map> json, {List<Map> selected, String hit = '请选择'}) {
    List<BaseBottomSheetSelectorModel> _items = BaseBottomSheetSelectorModel.getListBaseSelectDownItem(json);
    List<BaseBottomSheetSelectorModel> _selected;
    if (selected != null) {
      _selected = BaseBottomSheetSelectorModel.getListBaseSelectDownItem(selected);
    }
    return BaseBottomSheetMultipleController(items: _items, selected: _selected, hit: hit);
  }

  /// 弹出底部
  void showBottomSheet() {
    notifyListeners();
  }

  /// 是否选中
  bool isSelected(BaseBottomSheetSelectorModel v) {
    return selectedListString.contains(v.toString());
  }

  /// 改变选中值
  void changeSelected(BaseBottomSheetSelectorModel v) {
    this.isSelected(v) == true ? this.remove(v) : this.add(v);
  }

  /// 添加选中
  void add(BaseBottomSheetSelectorModel v) {
    if (!selectedListString.contains(v.toString())) {
      selected.add(v);
    }
  }

  /// 移除选中
  void remove(BaseBottomSheetSelectorModel v) {
    int index = selectedListString.indexOf(v.toString());
    if (index >= 0) {
      selected.removeAt(index);
    }
  }

  /// 重置选项
  void resetSelected() {
    this.selected = List<BaseBottomSheetSelectorModel>.from(this.oldSelected);
  }

  void setOldData(List<BaseBottomSheetSelectorModel> list) {
    this.oldSelected = List<BaseBottomSheetSelectorModel>.from(list);
  }
}
